package me.zhengjie.config.utils;


import cn.hutool.core.img.ImgUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.extra.qrcode.QrConfig;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import javax.imageio.ImageIO;
import javax.imageio.stream.ImageOutputStream;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;

public class QrCodeWithTextUtil {
    /**
     * 生成带文字的二维码图片
     * @param content 二维码内容
     * @param text 要添加的文字
     * @param outputPath 输出路径
     */
    public static void generateWithText(String content, String text,String outputPath) {

        // 文字位置，top表示文字在二维码上方，bottom表示文字在二维码下方
        String textPosition = "top";
        // 基本二维码配置
        QrConfig config = new QrConfig(300, 300);
        config.setMargin(2);
        config.setErrorCorrection(ErrorCorrectionLevel.H);

        // 生成原始二维码
        BufferedImage qrImage = QrCodeUtil.generate(content, config);

        // 创建带文字的合成图
        int textHeight = 30;
        BufferedImage combinedImage = new BufferedImage(
                qrImage.getWidth(),
                qrImage.getHeight() + textHeight,
                BufferedImage.TYPE_INT_RGB
        );

        Graphics2D g = combinedImage.createGraphics();
        g.setBackground(Color.WHITE);
        g.clearRect(0, 0, combinedImage.getWidth(), combinedImage.getHeight());

        // 计算文字位置
        int textY = textPosition.equalsIgnoreCase("top") ? textHeight : qrImage.getHeight();
        int qrY = textPosition.equalsIgnoreCase("top") ? textHeight : 0;

        // 绘制文字
        g.setColor(Color.BLACK);
        g.setFont(new Font("微软雅黑", Font.BOLD, 16));
        FontMetrics fm = g.getFontMetrics();
        int textX = (combinedImage.getWidth() - fm.stringWidth(text)) / 2;
        g.drawString(text, textX, textY - 10);
        // 绘制二维码
        g.drawImage(qrImage, 0, qrY, null);
        g.dispose();
        // 输出图片
        try {
            ImageOutputStream ios = ImageIO.createImageOutputStream(FileUtil.file(outputPath));
            ImgUtil.write(combinedImage, ImgUtil.IMAGE_TYPE_PNG, ios);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        generateWithText("https://hutool.cn", "扫码访问Hutool官网","d:/qrcode_with_text.png");
    }
}

